from itsdangerous import TimedJSONWebSignatureSerializer, BadData

from django.conf import settings


def generate_access_token(openid):
    '''接收openid，加密为access_token '''

    #1.创建对象
    s = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, expires_in=300)
    data = {
        'openid': openid
    }
    #2.加密
    token=s.dumps(data)#打印的值是bytes类型的
    #3.返回

    return token.decode()#转成string类型


def check_access_token(access_token):
    '''接收access_token,解密为openid'''
    # 1.创建对象
    s=TimedJSONWebSignatureSerializer(settings.SECRET_KEY,expires_in=300)
    #2.解密
    try:
        data=s.loads(access_token)

    except BadData:
        return None#解密失败返回空

    else:
        openid = data.get('openid')
        return openid